/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package linkeddata.arida.ufc.br.manager.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import linkeddata.arida.ufc.br.VCD.ElementsVCDS;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
 *
 * @author jeovane
 */
public class CreateCacheXMLFile {

    private Element SPARQLQuery = new Element("SPARQLQuery");
    private SAXBuilder builder = new SAXBuilder();
    private Document document;
    private Element ResultQuery;
    private File file;
    private String outXML;
    private static final String NODE_XML = "ResultQuery";
    private static final String ATTRIBUTE_CLASS = "class";
    private static final String ATTRIBUTE_KEY = "key";

    public CreateCacheXMLFile(File file, String outXML) {
        try {
            this.file = file;
            this.outXML = outXML;
            this.document = builder.build(file);
        } catch (JDOMException ex) {
            System.out.println("JDOMException: " + ex);
        } catch (IOException ex) {
            System.out.println("IOException: " + ex);
        }
    }

    public CreateCacheXMLFile(String outXML) {
        this.file = new File("");
        this.outXML = outXML;
    }

    // Cria o arquivo XML
    public void createDocQuery(String clazz, String key, String content) throws JDOMException, Exception {

        try {
            document = new Document();
            document.setRootElement(SPARQLQuery);

            if (!this.file.exists()) {
                elementsXML(clazz, key, content);
            } else if (this.file.exists()) {
                document = (Document) builder.build(this.file);
                List<Element> resultClasses = new ArrayList<Element>(document.getRootElement().getChildren(NODE_XML));
                existingKey(resultClasses);
                if (!existingKey(resultClasses).containsKey(key)) {
                    elementsXML(clazz, key, content);
                }
            } else {
                ResultQuery = new Element(NODE_XML);
            }

            File fileOutput = new File(System.getProperty("user.home") + "/" + System.getProperty("user.name") + "_" + outXML + ".xml");
            printDocument(document, new FileWriter(fileOutput));

        } catch (IOException io) {
            System.out.println("ERROR CreateXML: " + io.getMessage());
        }

        List<Element> resultClasses = new ArrayList<Element>(document.getRootElement().getChildren(NODE_XML));
        existingKey(resultClasses);

        if (ElementsVCDS.getExistingKey().keySet().isEmpty()) {
            for (String keyMap : existingKey(resultClasses).keySet()) {
                ElementsVCDS.setExistingKey(keyMap, valueKey(keyMap));
            }
        } else {
            ElementsVCDS.setExistingKey(key, valueKey(key));
        }

    }

    private Element elementsXML(String clazz, String key, String getQuery) {
        ResultQuery = new Element(NODE_XML);
        ResultQuery.setAttribute(new Attribute(ATTRIBUTE_CLASS, clazz));
        ResultQuery.setAttribute(new Attribute(ATTRIBUTE_KEY, key));
        ResultQuery.addContent(getQuery);
        document.getRootElement().addContent(ResultQuery);
        return ResultQuery;
    }

    // Adiciona os valores do arquivo XML em um Map
    private Map<String, String> existingKey(List<Element> resultClass) {
        Map<String, String> mapKeys = new HashMap<String, String>();
        for (Element e : resultClass) {
            String key = e.getAttributeValue(ATTRIBUTE_KEY);
            String value = e.getText();
            mapKeys.put(key, value);
        }
        return mapKeys;
    }

    // Retorna o valor de acordo com o valor da key contida no arquivo XML
    private String valueKey(String key) {
        List<Element> keys = new ArrayList<Element>(document.getRootElement().getChildren(NODE_XML));
        String value = "";
        for (Element child : keys) {
            String attrKey = child.getAttributeValue(ATTRIBUTE_KEY);
            if (attrKey.equals(key)) {
                value = child.getText();
            }
        }
        return value;
    }

    // Remove um nó do arquivo XML
    public void removerNode(List<Element> resultClasses, String removeKey) throws Exception {
        File fileOutput = new File(System.getProperty("user.home") + "/" + System.getProperty("user.name") + "_" + outXML + ".xml");
        Iterator<Element> iter = resultClasses.iterator();
        while (iter.hasNext()) {
            Element e = iter.next();
            if (e.getAttributeValue(ATTRIBUTE_CLASS).equals(removeKey)) {
                e.detach();
            }
        }
        printDocument(document, new FileWriter(fileOutput));
    }

    private void printDocument(Document document, FileWriter fileWriter) throws Exception {
        new XMLOutputter(Format.getPrettyFormat()).output(document, fileWriter);
    }
    
//    public static void main(String[] args) throws JDOMException, IOException, Exception {
//        String outXML = "abc";
//        File file = new File(System.getProperty("user.home") + "/" + System.getProperty("user.name") + "_" + outXML + ".xml");
//        CreateXMLFile createXMLFile;
//
//        if (!file.exists()) {
//            createXMLFile = new CreateXMLFile(outXML);
//            createXMLFile.createDocQuery("A", "Jeovane", "José Jeovane Reges Cordeiro");
//        } else {
//            createXMLFile = new CreateXMLFile(file, outXML);
//            createXMLFile.createDocQuery("B", "Mario", "Mario Cordeiro");
////            createXMLFile.createDocQuery("B", "Eduardo", "Pedro Eduardo");
//            //createXMLFile.createDocQuery("C", "Danilo", "Danilo Hits");
//            //createXMLFile.createDocQuery("C", "Pedro", "Pedro Henrique");
//            //System.out.println(createXMLFile.valueKey("Jeovane"));
//        }
//
//    }
}
